﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;

using System.Xml;
using System.Web;
using System.Web.Caching;
using System.Reflection;
using System.Configuration;
namespace Guru.Data
{
    public static class GuruConnectionString
    {
        public static string GetConnectionStrings(int clientID)
        {
            return GetConnectionStrings(clientID.ToString());
        }

        public static string GetConnectionStrings(string clientID)
        {
            //load xml & cache                
            string xmlFile = HttpContext.Current.Server.MapPath("~/App_Data/ConnectionStrings.xml");
            XmlDocument xmlDoc = null;
            if (HttpRuntime.Cache["Guru.Data.ConnectionString"] == null)
            {
                xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlFile);
                HttpRuntime.Cache.Add("Guru.Data.ConnectionString", xmlDoc, new CacheDependency(xmlFile), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
            }
            else
            {
                xmlDoc = (XmlDocument)HttpRuntime.Cache["Guru.Data.ConnectionString"];
            }

            XmlNode node = xmlDoc.SelectSingleNode(string.Format("//Client[@ClientID=\"{0}\"]/add[@name=\"GuruDB\"]", clientID));
            if (node == null)
            {
                node = xmlDoc.SelectSingleNode("//Client[@ClientID=\"default\"]/add[@name=\"GuruDB\"]");
            }
            return node.Attributes["connectionString"].InnerText;

        }

        public static string GetConnectionStrings()
        {
            return GetConnectionStrings(0);
        }

        public static string GetConnectionStrings(string key, bool webConfig)
        {
            if (ConfigurationManager.ConnectionStrings[key] == null)
            {
                throw new Exception("Invalid connection key");
            }
            return ConfigurationManager.ConnectionStrings[key].ConnectionString;
        }
    }
}
